package com.knight.admin.service;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;

import com.jfinal.log.Log;
import com.jfinal.log.Log4jLogFactory;
import com.knight.admin.common.constant.Constant;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

public class QiniuServiceImpl {

	private static final Logger logger = Logger.getLogger(QiniuServiceImpl.class);
	// 密钥配置
	private static Auth auth = Auth.create(Constant.QiniuConfig.ACCESS_KEY, Constant.QiniuConfig.SECRET_KEY);
	private static Configuration configuration =  new Configuration(Zone.zone2());
	// 创建上传对象
	private static UploadManager uploadManager = new UploadManager(configuration);
	private static BucketManager bucketMgr = new BucketManager(auth, configuration);

	// 覆盖上传
	private static String getUpToken(String key) {
		// <bucket>:<key>，表示只允许用户上传指定key的文件。在这种格式下文件默认允许“修改”，已存在同名资源则会被本次覆盖。
		// 如果希望只能上传指定key的文件，并且不允许修改，那么可以将下面的 insertOnly 属性值设为 1。
		// 第三个参数是token的过期时间
		return auth.uploadToken(Constant.QiniuConfig.BUCKET_NAME,
				key/* , 3600, new StringMap().put("insertOnly", 1) */);
	}

	public static boolean upload(File file, String key) throws IOException {
		try {
			// 调用put方法上传，这里指定的key和上传策略中的key要一致
			Response res = uploadManager.put(file, key, getUpToken(key));
			// 打印返回的信息
			System.out.println(res.bodyString());
		} catch (QiniuException e) {
			logger.error("key为"+key+"上传文件异常",e);
			Response r = e.response;
			// 请求失败时打印的异常的信息
			logger.error("key为"+key+"上传文件异常,响应信息:"+r.toString());
			try {
				// 响应的文本信息
				logger.error("key为"+key+"上传文件异常,响应正文:"+r.bodyString());
			} catch (QiniuException e1) {
				// ignore
			}
			return false;
		}
		return true;
	}

	public static boolean upload(String filePath, String key) throws IOException {
		try {
			// 调用put方法上传，这里指定的key和上传策略中的key要一致
			Response res = uploadManager.put(filePath, key, getUpToken(key));
			// 打印返回的信息
			System.out.println(res.bodyString());
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时打印的异常的信息
			System.out.println(r.toString());
			try {
				// 响应的文本信息
				System.out.println(r.bodyString());
			} catch (QiniuException e1) {
				// ignore
			}
			return false;
		}
		return true;
	}

	public static boolean deleteFile(String key) {
		try {
			bucketMgr.delete(Constant.QiniuConfig.BUCKET_NAME, key);
		} catch (Exception e) {
			logger.error("删除文件错误,key为"+key,e);
			return false;
		}
		return true;
	}

	public static void main(String[] args) throws IOException {
		
		 String localFilePath = "D:\\settings.txt"; upload(localFilePath,
		 "abc.txt");
		 

		/*if (deleteFile("1.jpg")) {
			logger.debug("删除成功");
		} else {
			logger.debug("删除失败");
		}*/
	}
}
